from homeassistant.config_entries import ConfigEntry
from homeassistant.core import CoreState, HomeAssistant
import homeassistant.helpers.config_validation as cv

from homeassistant.const import (
    EVENT_HOMEASSISTANT_STARTED,
    EVENT_STATE_CHANGED,
)

import json, time, logging
import paho.mqtt.client as mqtt
from .CryptoUtil import _encrypt, _decrypt

from .const import DOMAIN, PLATFORMS

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = cv.deprecated(DOMAIN)

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    config = entry.data
    wechat = WeChatNotificationService(hass, config.get('token'))
    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    return True

class WeChatNotificationService():
    def __init__(self, hass, uid):
        self.uid = uid
        if hass.state == CoreState.running:
            self.connect()
        else:
            hass.bus.listen_once(EVENT_HOMEASSISTANT_STARTED, self.connect)

    def connect(self, event=None):
        HOST = 'broker-cn.emqx.io'
        PORT = 1883
        client = mqtt.Client()        
        self.client = client
        client.on_connect = self.on_connect
        client.on_message = self.on_message
        client.on_subscribe = self.on_subscribe
        client.on_disconnect = self.on_disconnect
        client.connect(HOST, PORT, 60)
        client.loop_start()
        hass.services.async_register(DOMAIN, 'notify', self.notify)

    def on_connect(self, client, userdata, flags, rc):
        print('connectd')

    def on_message(self, client, userdata, msg):
        payload = str(msg.payload.decode('utf-8'))

    def on_subscribe(self, client, userdata, mid, granted_qos):
        print("On Subscribed: qos = %d" % granted_qos)

    def on_disconnect(self, client, userdata, rc):
        print("Unexpected disconnection %s" % rc)

    def publish(self, msg, link):
        # 判断当前连接状态
        if self.client._state == 2:
            _LOGGER.debug('断开重连')
            self.client.reconnect()
            self.client.loop_start()

        uid = self.uid
        topic_key = uid[8:24]
        payload = _encrypt(json.dumps({
            "msg_id": f'{topic_key}{time.time()}',
            "ctime": int(time.time()),
            "data": {
                "type": "text",
                "text": msg,
                "url": link
            }
        }), "", uid + time.strftime('%Y-%m-%d', time.localtime(time.time())))
        # print(payload)
        self.client.publish(f"shaonianzhentan/ha_push/{topic_key}", payload, qos=0)

    def notify(self, call):
        data = call.data
        self.publish(data.get('message', '测试消息'), data.get('url', ''))